package com.qiniuyun.threedgenerator.service.impl;

import com.qiniuyun.threedgenerator.dto.TextGenerationRequest;
import com.qiniuyun.threedgenerator.entity.ModelHistory;
import com.qiniuyun.threedgenerator.entity.User;
import com.qiniuyun.threedgenerator.repository.ModelHistoryRepository;
import com.qiniuyun.threedgenerator.repository.UserRepository;
import com.qiniuyun.threedgenerator.service.ModelGenerationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class ModelGenerationServiceImpl implements ModelGenerationService {

    private final ModelHistoryRepository modelHistoryRepository; // 修复：使用Repository接口
    private final UserRepository userRepository;

    @Override
    @Transactional
    public ModelHistory generateModel(TextGenerationRequest request, Long userId) {
        try {
            // 获取用户
            User user = userRepository.findById(userId)
                    .orElseThrow(() -> new RuntimeException("用户不存在: " + userId));

            // 创建模型历史记录
            ModelHistory modelHistory = new ModelHistory();
            modelHistory.setUser(user);
            modelHistory.setInputText(request.getText());
            modelHistory.setModelName(request.getModelName());
            modelHistory.setModelFormat(request.getFormat());
            modelHistory.setStatus("PROCESSING");

            // 保存初始记录
            ModelHistory savedHistory = modelHistoryRepository.save(modelHistory);

            log.info("开始生成3D模型，历史记录ID: {}", savedHistory.getId());

            // 这里添加实际的3D模型生成逻辑
            // 模拟生成过程
            simulateModelGeneration(savedHistory);

            return savedHistory;

        } catch (Exception e) {
            log.error("生成3D模型失败: {}", e.getMessage(), e);
            throw new RuntimeException("模型生成失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ModelHistory updateModelFeedback(Long historyId, Integer rating, String feedback, Long userId) {
        try {
            // 查找历史记录
            ModelHistory modelHistory = modelHistoryRepository.findByIdAndUserId(historyId, userId)
                    .orElseThrow(() -> new RuntimeException("模型历史记录不存在"));

            // 更新评分和反馈
            modelHistory.setUserRating(rating);
            modelHistory.setUserFeedback(feedback);
            modelHistory.setUpdatedAt(LocalDateTime.now());

            return modelHistoryRepository.save(modelHistory);

        } catch (Exception e) {
            log.error("更新模型反馈失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新反馈失败: " + e.getMessage());
        }
    }

    @Override
    public List<ModelHistory> getUserModelHistory(Long userId) {
        return modelHistoryRepository.findByUserId(userId);
    }

    @Override
    public Optional<ModelHistory> getModelHistoryById(Long id, Long userId) {
        return modelHistoryRepository.findByIdAndUserId(id, userId);
    }

    @Override
    public List<ModelHistory> getAllModelHistory() {
        return modelHistoryRepository.findAll();
    }

    // 模拟3D模型生成过程
    private void simulateModelGeneration(ModelHistory modelHistory) {
        try {
            // 模拟处理时间
            Thread.sleep(5000);

            // 更新状态为完成
            modelHistory.markAsCompleted();
            modelHistory.setModelPath("/models/" + modelHistory.getId() + "." + modelHistory.getModelFormat());

            modelHistoryRepository.save(modelHistory);

            log.info("3D模型生成完成，历史记录ID: {}", modelHistory.getId());

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            modelHistory.markAsFailed();
            modelHistoryRepository.save(modelHistory);
            log.error("模型生成被中断: {}", e.getMessage());
        } catch (Exception e) {
            modelHistory.markAsFailed();
            modelHistoryRepository.save(modelHistory);
            log.error("模型生成失败: {}", e.getMessage());
        }
    }
}